/*
 * @lc app=leetcode.cn id=297 lang=typescript
 *
 * [297] 二叉树的序列化与反序列化
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

/*
 * Encodes a tree to a single string.
 */
function serialize(root: TreeNode | null): string {
    let res: any = [];
    const loop = (root) => {
        if (!root) {
            res.push('none')
            return;
        }
        res.push(root.val);
        loop(root.left);
        loop(root.right);
    }

    loop(root);
    return res.toString();
};


/*
 * Decodes your encoded data to tree.
 */
function deserialize(data: string): TreeNode | null {
    const dataArr = data.split(',');
    
    const loop = (datalist: any) => {
        if (datalist[0] === 'none') {
            datalist.shift();
            return null;
        }
        const root = new TreeNode(Number(datalist[0]));
        datalist.shift();
        root.left = loop(datalist);
        root.right = loop(datalist);

        return root
    }
    
    return loop(dataArr)
};


/**
 * Your functions will be called as such:
 * deserialize(serialize(root));
 */
// @lc code=end

